package com.lx.errorHanding.overview;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * SpringBatch 默认情况下的错误机制（终止一个job的执行）
 * @author lixing
 * @date 2021/7/13 14:16
 */
@Configuration
public class ErrorHandingOverviewJobConfigration {
    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public Job errorHandingOverviewJob(){
        return jobBuilderFactory.get("errorHandingOverviewJob")
                .start(step1())
                .next(step2())
                .build();
    }

    @Bean
    public Step step2() {
        return stepBuilderFactory.get("step2")
                .tasklet(errorHandingOverviewTasklet())
                .build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")
                .tasklet(errorHandingOverviewTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet errorHandingOverviewTasklet() {
        return new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                Map<String, Object> stepExecutionContext = chunkContext.getStepContext().getStepExecutionContext();

                if (stepExecutionContext.containsKey("first")){
                    System.out.println("Second run will success ...");
                    return RepeatStatus.FINISHED;
                }else {
                    System.out.println("First run will fail ...");
                    ExecutionContext executionContext = chunkContext.getStepContext().getStepExecution().getExecutionContext();
                    executionContext.put("first",true);
                    throw new RuntimeException("Error occurs...");
                }
            }
        };
    }

}
